package com.duguo.dynamicmvc.support.pathinfo;


public class PathInfoImpl implements PathInfo {

    private static final String DEFAULT = "index";

    private String[] _paths;

    private int _currentPosition = 0;
    private String _servletPath;

	private String _extension;

    public PathInfoImpl(String servletPath) {
        _servletPath = servletPath;
        if (servletPath.length() <= 1)
            _paths = new String[0];
        else{
            _paths = servletPath.substring(1).split("/");
            
            setupExtension();
        }
    }


    public String getCurrentServlet() {
        return getPath(_currentPosition);
    }


    public String getRemainPath() {
    	StringBuffer remailPath=new StringBuffer();
    	if (_currentPosition < _paths.length){
    		for(int i=_currentPosition;i<_paths.length;i++){
    			if(remailPath.length()>0)
    				remailPath.append("/");
    			remailPath.append(_paths[i]);
    		}
    		if(_extension!=null) {
    			remailPath.append(".");
    			remailPath.append(_extension);
    		}
            return remailPath.toString();
    	}else
    		return null;
    }


    public void increasePosition() {
        _currentPosition++;
    }


    public int getCurrentPosition() {
        return _currentPosition;
    }


    public String getRelativePath(int relativePosition) {
    	relativePosition=relativePosition+_currentPosition;
    	return getPath(relativePosition);
    }


    public String getPath(int position) {
        if (position < _paths.length)
            return _paths[position];
        else
            return DEFAULT;
    }


    public String[] getPaths() {
        return _paths;
    }


    /*
     * e.g. /foo1/foo2/foo3 
     * getPaths(4)=/foo1/foo2/foo3/
     * getPaths(1)=/
     */
    public String getPaths(int level) {
    	level--;
    	StringBuffer sb=new StringBuffer("/");
    	if(level>0){
    		int temp_pos=0;
    		if(level>_paths.length)
    			level=_paths.length;
    			
	    	while(temp_pos<level){
	    		sb.append(_paths[temp_pos]);
	    		sb.append("/");
	    		temp_pos++;
	    	}
    	}
        return sb.toString();
    }


    public String getServletPath() {
        return _servletPath;
    }


	public String getExtension() {
		return _extension;
	}
	
	private void setupExtension() {
		int lastPathPosition=_paths.length-1;
		int position=_paths[lastPathPosition].indexOf(".");
		if(position!=-1){
			_extension=_paths[lastPathPosition].substring(position+1);
			_paths[lastPathPosition]=_paths[lastPathPosition].substring(0,position);
		}
	}
	
	public String toString(){
		return _servletPath;
	}
}
